package com.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Date: 2024/7/23 15:47
 * Author: T_log
 * Description: ReadWriteLockDemo
 */
public class ReadWriteLockDemo {


    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181",
                5000,
                3000,
                retryPolicy);


        client.start();
        System.out.println("已经成功的连接ZK服务了....");

        //代码二、这里会创建两把锁，在/locks/lock路径下，一把写锁，一把读锁
        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(client,"/locks/lock");

        // 返回InterProcessMutex对象
        InterProcessMutex writeLock = readWriteLock.writeLock();
        // 进行加锁，代码三、
        writeLock.acquire();
        writeLock.release();

        InterProcessMutex readLock = readWriteLock.readLock();
        readLock.acquire();
        readLock.release();


        Thread.sleep(Integer.MAX_VALUE);
    }
}
